<?php
	class UploadController extends Controller {
		public function actionIndex() {
			$this->render(
				'upload',
				array(
					'message' => 'please select a book to upload'
				)
			);
		}
		
		public function actionUpload() {
			$message = 'Please select an ebook to upload';
			try {
					if (isset($_FILES['file']['name'][0])) {
						$book = new Book();
						// book name
						move_uploaded_file(
							$_FILES['file']['tmp_name'][0],
							'resource/'.$_FILES['file']['name'][0]
						);
						$book->name = $_FILES['file']['name'][0];
						// book cover
						if ($_FILES['file']['name'][1] != null) {
							move_uploaded_file(
								$_FILES['file']['tmp_name'][1],
								'imagebooks/'.$_FILES['file']['name'][1]
							);
							$book->urlimage = 'imagebooks/'.$_FILES['file']['name'][1];
						}
						// book description
						$book->description = $_POST['description'];
						// book created date
						$book->createddate = new CDbExpression('NOW()');
						// user's ID
						$book->iduser = Yii::app()->user->id;
						// book check
						$book->check = 0;
						// book url
						$book->resource = 'resource/'.$_FILES['file']['name'][0];
						// book's author
						$book->author = $_POST['author'];
						// save book record
						$book->save();
						
						// assign genres to the book
						if (isset($_POST['genreList'])) {
							foreach($_POST['genreList'] as $genre) {
								if ($genre == true) {
									$book_genre = new BookGenre();
									$book_genre->idgenre = $genre;
									$book_genre->idbook = $book->idbook;
									if(!$book_genre->save())$message = "$book_genre->getErrors()";
								}
							}
						}
						
						$message = $_FILES['file']['name'][0].' is uploaded<br/>';
					}
				} catch (Exception $e) {
					
				}
			$this->render('upload', array('message' => $message));
		}
		
		public function filters() {
			return array(
				'accessControl'
			);
		}
		
		public function accessRules() {
				return array(
				array('allow',
					'users'=>array('@'),
				),
				array('deny',
					'users'=>array('*'),
				),
			);
		}
	}
?>